class Order < ActiveRecord::Base
  
  has_many :order_items
  belongs_to :restaurant
  belongs_to :orderee, :class_name => "User"
  
  validates_presence_of :state, :restaurant
  
  acts_as_state_machine :initial=>:open
  state :open
  state :closed
  state :delivered
  
  event :close do
    transitions :from => :open, :to => :closed 
  end
  
  event :deliver do
    transitions :from => :open, :to => :delivered
  end
  
  def add (dish, count)
    if dish.restaurant.eql? self.restaurant
      order_item = OrderItem.new :order=>self, :dish=>dish, :count=>count
      self.order_items << order_item
      self.total_price += dish.price * count
    else
      raise 'the dish should be from the same restaurant!'
    end
  end
  
  def item_count
    self.order_items.length
  end
  
  def delivered?
    self.state.eql? "delivered"
  end
  
end
